package cc.iteachyou.template.taglib.directives;

import cc.iteachyou.template.dom.VirtualDOMAttr;
import cc.iteachyou.template.dom.VirtualDOMNode;
import cc.iteachyou.template.taglib.IDirectiveHandler;
import cc.iteachyou.template.taglib.result.DirectiveResult;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ForDirectiveHandler implements IDirectiveHandler {
    @Override
    public Optional<DirectiveResult> handler(VirtualDOMNode.RendererVirtualDOMAttrContext ctx, Map<String, Object> data) {
        VirtualDOMAttr attr = ctx.getAttr();
        VirtualDOMNode node = ctx.getNode();

        String value = attr.getValue();

        Pattern pattern = Pattern.compile("(.*)?[\\s]{0,}:[\\s]{0,}(#.*)");
        Matcher matcher = pattern.matcher(value);
        if(!matcher.find()){
            throw new RuntimeException("For loop syntax error.");
        }
        String item = matcher.group(1);
        String list = matcher.group(2);

        Object eval = engine.eval(list, data);

        Map<String, Object> loop = new HashMap<>();
        loop.put("item", item);
        loop.put("list", eval);

        DirectiveResult result = DirectiveResult.builder()
                .name(attr.getName())
                .value(attr.getValue())
                .loopData(loop)
                .build();
        return Optional.of(result);
    }
}
